package com.euq.utils;

import com.euq.dto.MenuDto;
import com.euq.entity.Menu;

import java.util.*;

public class MenuTreeBuilder {
    public static List<MenuDto> buildMenuTree(List<Menu> menuList) {
    Map<String, MenuDto> dtoMap = new HashMap<>();


    for (Menu menu : menuList) {
        MenuDto dto = new MenuDto();
        copyMenu(menu, dto);
        dtoMap.put(dto.getCode(), dto);
    }

    List<MenuDto> rootList = new ArrayList<>();


    for (MenuDto dto : dtoMap.values()) {
        String pCode = dto.getpCode();
        if (pCode == null || pCode.isEmpty() || !dtoMap.containsKey(pCode)) {
            rootList.add(dto);
        } else {
            MenuDto parent = dtoMap.get(pCode);
            parent.getChildren().add(dto);
        }
    }

    sortTreeByNum(rootList);

    return rootList;
}

    private static void copyMenu(Menu src, MenuDto dest) {
        dest.setId(src.getId());
        dest.setCode(src.getCode());
        dest.setComponent(src.getComponent());
        dest.setHidden(src.getHidden());
        dest.setIcon(src.getIcon());
        dest.setIsMenu(src.getIsMenu());
        dest.setIsOpen(src.getIsOpen());
        dest.setLevels(src.getLevels());
        dest.setName(src.getName());
        dest.setNum(src.getNum());
        dest.setpCode(src.getpCode());
        dest.setpCodes(src.getpCodes());
        dest.setTips(src.getTips());
        dest.setUrl(src.getUrl());
    }

    private static void sortTreeByNum(List<MenuDto> nodes) {
        nodes.sort(Comparator.comparingLong(MenuDto::getNum));
        for (MenuDto node : nodes) {
            if (!node.getChildren().isEmpty()) {
                sortTreeByNum(node.getChildren());
            }
        }
    }
}
